﻿using PLCS.App.UserAuthorization;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Application.Contracts.UserApp.Dtos;
using PLCS.Client.IService.LogManager;

namespace ZFGG_JTX_PLCS.App.UserAuthorization.ViewModels.User;

public class UserDetailViewModel : HostDialogViewModel
{
    #region 字段

    private ObservableCollection<string> _canSelectItems;
    private string _selectItem;
    private readonly IUserService _userService;
    private readonly IRoleService _roleService;
    private readonly IObjectMapper<UserAuthorizationModule> _objectMapper;
    private readonly IOperationLogService _logShowService;
    private UserDto _model;
    private ObservableCollection<string> _selectedItems;
    private bool _isItemDialogOpen;

    public bool IsItemDialogOpen
    {
        get { return _isItemDialogOpen; }
        set { SetProperty(ref _isItemDialogOpen, value); }
    }

    public ObservableCollection<string> CanSelectItems
    {
        get { return _canSelectItems; }
        set { SetProperty(ref _canSelectItems, value); }
    }

    public string SelectItem
    {
        get { return _selectItem; }
        set { SetProperty(ref _selectItem, value); }
    }

    public ObservableCollection<string> SelectedItems
    {
        get { return _selectedItems; }
        set { SetProperty(ref _selectedItems, value); }
    }

    public UserDto Model
    {
        get { return _model; }
        set { SetProperty(ref _model, value); }
    }

    #endregion 字段

    #region DelegateCommand

    /// <summary>
    /// 添加权限
    /// </summary>
    public DelegateCommand AddItemCommand => new DelegateCommand(() =>
    {
        SelectedItems.Add(SelectItem);
        IsItemDialogOpen = false;
    });

    /// <summary>
    /// 删除权限
    /// </summary>
    /// <param name="index"></param>
    public DelegateCommand<object> DeleteItemCommand => new DelegateCommand<object>(index =>
    {
        SelectedItems.RemoveAt(int.Parse(index.ToString()));
    });

    public DelegateCommand CloseItemDialogCommand => new DelegateCommand(() => IsItemDialogOpen = false);
    public DelegateCommand OpenItemDialogCommand => new DelegateCommand(() => IsItemDialogOpen = true);

    public DelegateCommand DropOpenedCommand => new DelegateCommand(DropOpened);

    /// <summary>
    /// 下拉刷新可添加权限
    /// </summary>
    private async void DropOpened()
    {
        try
        {
            CanSelectItems = new ObservableCollection<string>();
            var res = await _roleService.GetListAsync();
            foreach (var item in res)
            {
                if (!SelectedItems.Contains(item.RoleName))
                    CanSelectItems.Add(item.RoleName);
            }
        }
        catch (Exception ex)
        {
            CanSelectItems = null;
        }
    }

    #endregion DelegateCommand

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        SelectedItems = new ObservableCollection<string>();
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<UserDto>("Value");
            if (!string.IsNullOrEmpty(Model.RolesString))
                foreach (var item in Model.RolesString.Split(ConstantChar.SplitChar))
                {
                    SelectedItems.Add(item);
                };
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new UserDto();
        }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            var user = _objectMapper.Map<UserDto, UserEditDto>(Model);
            string res = "";
            for (int i = 0; i < SelectedItems.Count; i++)
            {
                if (i == SelectedItems.Count - 1)
                {
                    res += $"{SelectedItems[i]}";
                    continue;
                }
                res += $"{SelectedItems[i]}{ConstantChar.SplitChar}";
            }
            user.RolesString = res;
            if (user.Id != Guid.Empty)
                await _userService.UpdateAsync(user);
            else
                await _userService.CreateAsync(user);
            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage("操作失败");
        }
        finally { SavebuttonIsEnabled = true; }
    }

    public UserDetailViewModel(IUserService userService, IRoleService roleService, IObjectMapper<UserAuthorizationModule> objectMapper, IOperationLogService logShowService)
    {
        _userService = userService;
        _roleService = roleService;
        this._objectMapper = objectMapper;
        this._logShowService = logShowService;
    }
}